<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="产品库名称" prop="productlibraryId" class="w-250">
        <el-select v-model="queryParams.productlibraryId" placeholder="请选择产品库名称" clearable @change="handleQuery" multiple>
          <el-option v-for="dict in libraryNameList" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="产品名称" prop="contentName" class="w-250">
        <el-input v-model="queryParams.contentName" placeholder="请输入产品名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="是否有效" prop="isStatus" class="w-250">
        <el-select v-model="queryParams.isStatus" placeholder="请选择是否有效" clearable @change="handleQuery">
          <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="分类" prop="productClassifyName" class="w-250">
        <el-input v-model="queryParams.productClassifyName" placeholder="请输入产品名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="产品库" prop="isStatus" class="w-250">
        <el-select v-model="queryParams.isStatus" placeholder="请选择是否有效" clearable @change="handleQuery">
          <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="创建人" prop="createBy" class="w-250">
        <el-input v-model="queryParams.createBy" placeholder="请输入创建人" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-hasPermi="['manage:content:add']">
        <el-button type="primary" size="small" icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['manage:content:remove']">
        <el-button type="danger" size="small" icon="Delete" :disabled="multiple" @click="handleDelete"
          >删除</el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['manage:content:import']">
        <el-button type="info" icon="upload" size="small" @click="handleImport"
          >导入</el-button>
      </el-col>
      <el-col :span="1.5" v-hasPermi="['manage:content:export']">
        <el-button type="warning" size="small" icon="Download" @click="handleExport"
          >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="contentList" @selection-change="handleSelectionChange"
      @cell-click="(row) => { console.log('当前行信息：', row) }">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="60" />
      <el-table-column label="产品ID" align="center" prop="id" width="100" />
      <el-table-column label="产品名称" align="center" prop="contentName" width="150" />
      <!-- <el-table-column label="父级产品分类" align="center" prop="productclassifyName" width="150">
        <template #default="scope">
          <el-tag v-for="item in scope.row.productClassifyName" :key="item" type="primary"> {{ item }}</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="父级产品库名称" align="center" prop="libraryName" width="120" />
      <el-table-column label="父级分类名称" align="center" prop="classityName" width="120" />
      <el-table-column label="存储方式" align="center" prop="saveMethodContent" width="120" />
      <el-table-column label="效期类型" align="center" prop="expiryType" width="120" />
      <el-table-column label="保质期" align="center" prop="qualityPeriod">
        <template #default="scope">
          <span>
            {{ `${scope.row.qualityPeriod}${scope.row.dateType}` }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="时间格式" align="center" prop="dateFormat" width="180" />
      <el-table-column label="标签类型" align="center" prop="labelContent" width="120">
        <template #default="scope">
          <span>
            {{ scope.row.labelContent === '1' ? '效期标签':'自定义标签' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="产品备注" align="center" prop="contentFlag"/>
      <el-table-column label="状态" align="center" prop="isStatus">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.isStatus" type="tag" />
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" sortable />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
        <template #default="scope">
          <el-link icon="Edit" class="table_link_btn" type="primary" :underline="false" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:content:edit']"><span class="table_link_text">修改</span></el-link>
          <el-link icon="Delete" class="table_link_btn" type="danger" :underline="false" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:content:remove']"><span class="table_link_text">删除</span></el-link>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改产品库产品对话框 -->
    <el-dialog :title="title" v-model="open" width="40%" append-to-body class="content-dialog" draggable destroy-on-close @close="cancel">
      <el-form ref="contentRef" :model="form" :rules="rules" label-width="120px" label>

        <el-form-item label="产品分类" prop="productclassifyId">
          <el-select v-model="form.productclassifyId" :multiple-limit="3" multiple filterable class="w-300">
            <el-option v-for="library in classifyList" :value="library.id" :key="library.id" :label="library.name"
              :disabled="library.isStatus === '1'" />
          </el-select>
        </el-form-item>

        <el-form-item label="产品名称" prop="contentName" >
          <el-input v-model="form.contentName" placeholder="请输入产品名称" class="w-300"/>
        </el-form-item>

        <el-form-item label="产品图片">
          <image-upload @imageTouch="(e: any) => { form.productPic = e }" :imageUrl="form.productPic" />
        </el-form-item>

        <el-form-item label="产品备注" prop="contentFlag">
          <el-input v-model="form.contentFlag" placeholder="标识 (只做前台标识不打印)" class="w-300" />
        </el-form-item>

        <!-- <el-form-item label="标签类别" prop="labelContent">
          <el-radio-group v-model="form.labelContent">
            <el-radio v-for="dict in content_label_type" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item> -->
        
        <el-form-item label="排序" prop="productSort">
          <el-input-number v-model="form.productSort" controls-position="right" :min="0"  class="w-300"/>
        </el-form-item>
        

        <el-form-item label="产品状态" prop="isStatus">
          <el-radio-group v-model="form.isStatus">
            <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item prop="restrictedPrintRecordcount">
          <template #label>
            <span>
              <el-tooltip content="注:当数量为0时则不限制打印数量" placement="top">
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
              限制打印数
            </span>
          </template>
          <el-input-number v-model="form.restrictedPrintRecordcount" controls-position="right" :min="0" class="w-300" />
        </el-form-item> -->
        <el-form-item label="预警时间" prop="earlyWarning">
          <template #label>
            <span>
              <el-tooltip content="注:产品过期前N分钟提醒，跟随门店默认过期前30分钟" placement="top">
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
              预警时间
            </span>
          </template>
          <el-select v-model="form.earlyWarning" class="w-300">
            <el-option v-for="option in options.earlyWarning" :key="option.value" :label="option.label"
              :value="option.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="提前预警(分钟)" prop="earlyWarningDate" v-if="form.earlyWarning === '1'" >
          <el-input-number v-model="form.earlyWarningDate" controls-position="right" :min="1" class="w-300"/>
        </el-form-item>

        <el-form-item prop="templateId">
          <template #label>
            <span>
              <el-tooltip content="注:门店端打印的样式" placement="top">
                <el-icon><question-filled /></el-icon>
              </el-tooltip>
              打印模版
            </span>
          </template>
          <el-select v-model="form.templateId" class="w-300" @change="(e)=>changeTemplate(e,'change')">
            <el-option v-for="temp in templateList" :key="temp.id" :label="`${temp.templateName}(${temp.printerSize})`"
              :value="temp.id" />
          </el-select>
          <el-tooltip
            :content="form.templateId ? generateHtml(JSON.parse(templateList.find((ele: any) => ele.id === form.templateId)['templateContent'])) : '<span>暂无模版，请选择</span>'"
            raw-content placement="right">
            <span class="text-blue cursor-pointer ml-20">显示模版</span>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="时间格式" prop="dateFormat">
          <el-select v-model="form.dateFormat" class="w-300">
            <el-option v-for="option in options.dateFormat" :key="option.label" :label="option.label"
              :value="option.label" />
          </el-select>
        </el-form-item>
        <template v-if="filterTemplateType === '1'">
          <el-form-item label="效期类型" prop="expiryType">
            <el-select v-model="form.expiryType" class="w-300">
              <el-option v-for="option in options.expiryType" :key="option.label" :label="option.label"
                :value="option.label" />
            </el-select>
          </el-form-item>
          <el-form-item label="存储时间" prop="qualityPeriod">
            <el-input-number v-model="form.qualityPeriod" controls-position="right" :min="1" class="w-300"/>
          </el-form-item>
          <el-form-item label="时间类型" prop="dateType">
            <el-select v-model="form.dateType" class="w-300">
              <el-option v-for="option in options.dateType" :key="option.label" :label="option.label"
                :value="option.label" :disabled="option.status"/>
            </el-select>
          </el-form-item>
        </template>

        <el-form-item v-for="(item, index) in filteredOptions" :key="index" :label="item.label" :prop="item.prop">
          <el-input v-if="item.type === 'text'" v-model="form[item.prop]" type="text" class="w-300"/>
          <el-input-number v-if="item.type === 'number'" v-model="form[item.prop]" controls-position="right" :min="1" class="w-300"/>
          <el-select v-if="item.type === 'selectAndInput'" v-model="form[item.prop]" filterable allow-create
            default-first-option :reserve-keyword="false" class="w-300">
            <el-option v-for="option in options[item.prop]" :key="option.label" :label="option.label"
              :value="option.label" />

          </el-select>
          <el-select v-if="item.type === 'select'" v-model="form[item.prop]" class="w-300">
            <el-option v-for="option in options[item.prop]" :key="option.label" :label="option.label"
              :value="option.label" :disabled="option.status" />
          </el-select>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
     <!-- 用户导入对话框 -->
     <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body @close="cleanUploadRef()" :loading="true">
            <el-upload v-loading="upload.loading" ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag status="uploading">
                <i class="upload"></i>
                <div class="el-upload__text">
                    将文件拖到此处，或
                    <em>点击上传</em>
                </div>
                <template v-slot:tip>
                    <div class="el-upload__tip">
                        <!-- <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据 -->
                  <div class="el-upload__tip text-red">提示：仅允许导入“xls”或“xlsx”格式文件！<span @click="importTemplate" class="text-blue cursor-pointer">下载模板</span> </div>
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm">确 定</el-button>
                    <el-button @click="upload.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
  </div>
</template>

<script setup name="Content" lang="ts">
import { computed, getCurrentInstance, reactive, ref, watch } from 'vue';
import { generateHtml } from '@/utils/generateHtml';
import useContent from '@/api/request/manage/content/index';
import useBase from '@/api/request/manage/content/useBase';
import useImport from './composition/useImport';
import { listLibrary, qyListLibrary } from '@/api/manage/library';
import useUserStore from '@/store/modules/user';
import { listClassify, qyListClassify } from '@/api/manage/classify';
const { proxy } = getCurrentInstance() as any;

const { sys_normal_disable } = proxy.useDict('sys_normal_disable');
const { content_label_type } = proxy.useDict('content_label_type');
const options = reactive({
	saveMethodContent: [{ label: '常温储存', value: '常温储存', status: false }, { label: '冷藏储存', value: '冷藏储存', status: false }, { label: '冷冻储存', value: '冷冻储存', status: false }],
	'expiryType': [{ label: '自然日期', value: '自然日期', status: false }, { label: '打烊废弃', value: '打烊废弃', status: false }],
	dateType: [{ label: '天', value: '天', status: false }, { label: '小时', value: '小时', status: false }, { label: '分钟', value: '分钟', status: false }],
	dateFormat: [{ label: 'YYYY-MM-DD HH:mm' }, { label: 'YYYY/MM/DD HH:mm' }, { label: 'YYYY年M月D日 HH时mm分' }, { label: 'YYYY-MM-DD' }, { label: 'YYYY/MM/DD' }, { label: 'YYYY年M月D日' }],
	earlyWarning: [{ label: '跟随门店', value: '0' }, { label: '自定义', value: '1' }, { label: '不提醒', value: '2' }],
});
const form = ref<any>({});
const rules = reactive<any>({});
const classifyList = ref<any>('');

const { templateList, filteredOptions, selectShowList,changeTemplate ,filterTemplateType} = useContent(form);
const {roles} = useUserStore();
const { handleSubmit, handleUpdate, handleAdd, handleExport, handleDelete, getList, handleQuery, resetQuery, handleSelectionChange, cancel, title, open, total, queryParams, loading, multiple, showSearch, contentList, single, queryRef } = useBase(form,changeTemplate);
const {handleImport,cleanUploadRef,importTemplate,handleFileSuccess,handleFileUploadProgress,submitFileForm,upload,uploadRef } = useImport(getList);
async function getAllLibrary (){

	if(roles.includes('areaAdmin')){
		const response = await qyListLibrary();
		const classResponse = await qyListClassify();
	  libraryNameList.value = response.data.list.map((ele:any)=>{return{name:ele.productlibraryName,id:ele.id};});
	  classifyList.value = classResponse.data.list.map((ele:any)=>{return{name:ele.classifyName,id:ele.id};});
		return;
	}
	const response = await listLibrary();
	const classResponse = await listClassify();
	libraryNameList.value = response.data.list.map((ele:any)=>{return{name:ele.productlibraryName,id:ele.id};});
	classifyList.value = classResponse.data.list.map((ele:any)=>{return{name:ele.classifyName,id:ele.id};});

	console.log(libraryNameList.value,'p-pp-');
  
}
getAllLibrary();
getList();
const libraryNameList = ref<any>([]);


watch(() => form.value.expiryType, (newVal) => {
	if (newVal === '打烊废弃') {
		form.value.dateType = '天';
		options.dateType.forEach(data => {
			if (data.label !== '天') {
				data.status = true;
			}
		});
	}
	if (newVal === '自然日期') {
		options.dateType.forEach(data => {
			data.status = false;
		});
	}
});
watch(form, (newVal) => {
	const keyList = Object.keys(newVal);
	keyList.forEach(ele => {
		let writeList = ['id', 'contentFlag', 'productPic'];
		if (!writeList.includes(ele)) {
			rules[ele] = [
				{ required: true, message: '请输入对应值！', trigger: 'blur' },
			];
		}

	});
});

</script>
<style lang="scss" scoped>
// .el-select,.el-input,.el-input-number {
//   width: 300px !important;
// }
.templateContent {
  display: flex;
  /* justify-content: space-around; */
  width: 100%;
  border: 1px solid #d7dae2;
  border-radius: 10px;
  box-sizing: border-box;
  padding: 10px;
  height: 300px;
  flex-wrap: wrap;
  overflow: auto;

  li {
    background-color: #d7dae2;
    margin: 0 10px 10px 0;
    // transform: scale(0.6);
    // transform-origin: top left; /* 指定缩放的基准点为左上角 */
    list-style: none;
    cursor: pointer;
    transition: all linear .5s;
    text-align: center;
    border-radius: 10px;

    pos &:hover {
      background-color: rgb(220, 220, 220);
    }
  }

}

.isActive {
  border: 2px solid #3893fd;
}

page {
  text {
    display: block;
  }
}
</style>
